const {PDFDocument, StandardFonts, rgb} = require("pdf-lib")
const fs = require("fs/promises")
const fs1 = require("fs");
const path = require("path")

async function startTransform(filename=""){

    //原始文件名
    const sourcePdfFileName = filename;
    //原始文件路径
    const pdffilepath = path.resolve(__dirname,"pdf",sourcePdfFileName);
    console.log("get original pdf file at path : "+pdffilepath);
    if(!fs1.existsSync(pdffilepath)){
        console.log("\nfile is not found at path : "+pdffilepath)
        return
    }
    //生成文件路径
    const newpdffilepath = path.resolve(__dirname,"output","updated_"+sourcePdfFileName);

    const pdfData = await fs.readFile(pdffilepath);
    var pdfdoc = await PDFDocument.load(pdfData);
    var pagesize = pdfdoc.getPages().length
    console.log("\ngot pdf file total page number : "+pdfdoc.getPages().length);

    var udpatedFileBytes = await pdfdoc.save()
    var newpdfdoc = await PDFDocument.load(udpatedFileBytes);
    console.log("start cropping")
    const cropScale = 0.53;
    
    var newPageSize = newpdfdoc.getPages().length;
    console.log("\nnew page size is : "+newPageSize)
            //draw water mark
    const drawTextOffsetX = 20;//文字和最底部左边留20像素间距
    var drawTextOffsetY = 35;//文字和最底部留10像素间距
    const drawText = "MADE IN CHINA";// watermark text
    const watermarkColor = rgb(0,0,0);//r,g,b value vary from 0 to 1, decimal
    const watermarkFont = await newpdfdoc.embedFont(StandardFonts.Helvetica);
    const watermarkFontSize = 18;    

    for (var j = 0; j < newPageSize; j++){
            var page = newpdfdoc.getPage(j);
            var originHeight = page.getHeight();
            if(j== 0){
                console.log("\norigin height is : "+originHeight)
            }
            var width = page.getWidth();
            //左下角 原点坐标(0,0)
            const targetLeftCornerX = 0;
            const targetLeftCornerY = originHeight * (1-cropScale);
            page.setCropBox(targetLeftCornerX,targetLeftCornerY, width, originHeight * cropScale);      

            page.drawText(drawText,{
                x:drawTextOffsetX,
                y:targetLeftCornerY+drawTextOffsetY,
                font:watermarkFont,
                size:watermarkFontSize,
                color:watermarkColor
            })

    }

    const newPdfBytes = await newpdfdoc.save();

    var fileExists = fs1.existsSync(newpdffilepath)
    if(fileExists){
        fs1.rmSync(newpdffilepath);
    }
    await fs.writeFile(newpdffilepath,newPdfBytes);

}

const folder = path.resolve(__dirname,"pdf");

fs1.readdir(folder,(err,files)=>{
    if(err){
        console.log("got error"+err)
        return;
    }
    files.forEach((file,idx,arr)=>{
        var filename = file
        if(filename.endsWith(".pdf")){
            startTransform(filename)
        }
    })
})
